#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
综合评分与排序系统 - 第五步执行模块
建立多因子评分模型，选出Top 3潜力股票
"""

import sys
import os
import pandas as pd
import numpy as np
from datetime import datetime, timedelta
import warnings
warnings.filterwarnings('ignore')

sys.path.append(os.path.dirname(os.path.abspath(__file__)))

class ComprehensiveRankingSystem:
    """综合评分与排序系统"""
    
    def __init__(self):
        # 多因子权重配置
        self.factor_weights = {
            'screening_score': 0.15,    # 筛选评分权重
            'technical_score': 0.30,    # 技术面权重
            'fundamental_score': 0.40,  # 基本面权重
            'dividend_bonus': 0.10,     # 分红奖励权重
            'risk_adjustment': 0.05     # 风险调整权重
        }
        
        # 风险评估参数
        self.risk_factors = {
            'high_pe_threshold': 25,    # 高PE风险阈值
            'low_liquidity_threshold': 50,  # 低流动性风险阈值
            'high_volatility_threshold': 30,  # 高波动性风险阈值
        }
        
    def print_header(self, title):
        """打印标题"""
        print(f"\n{'='*80}")
        print(f"🎯 {title}")
        print(f"{'='*80}")
        
    def load_fundamental_results(self, filename="fundamental_analysis_results.csv"):
        """加载基本面分析结果"""
        try:
            df = pd.read_csv(filename)
            return df.to_dict('records')
        except Exception as e:
            print(f"加载基本面分析结果失败: {e}")
            return []
            
    def calculate_dividend_bonus(self, stock_info):
        """计算分红奖励评分"""
        try:
            has_dividend = stock_info.get('has_dividend', False)
            dividend_count = stock_info.get('dividend_count', 0)
            dividend_yield = stock_info.get('dividend_yield', 0)
            dividend_quality = stock_info.get('dividend_quality', '无分红')
            
            if not has_dividend:
                return 0
                
            bonus_score = 0
            
            # 分红历史奖励
            if dividend_count >= 5:
                bonus_score += 30
            elif dividend_count >= 3:
                bonus_score += 20
            elif dividend_count >= 1:
                bonus_score += 10
                
            # 分红收益率奖励
            if dividend_yield >= 5:
                bonus_score += 25
            elif dividend_yield >= 3:
                bonus_score += 15
            elif dividend_yield >= 1:
                bonus_score += 5
                
            # 分红质量奖励
            quality_bonus = {
                '优秀': 20,
                '良好': 10,
                '一般': 5,
                '较差': 0,
                '无分红': 0
            }
            bonus_score += quality_bonus.get(dividend_quality, 0)
            
            return min(bonus_score, 75)  # 最高75分
            
        except Exception as e:
            print(f"计算分红奖励失败: {e}")
            return 0
            
    def assess_risk_factors(self, stock_info):
        """评估风险因素"""
        try:
            pe_ratio = stock_info.get('pe_ratio', 15)
            market_cap = stock_info.get('market_cap', 100)
            current_price = stock_info.get('current_price', 10)
            
            risk_score = 0  # 风险评分，负数表示风险
            risk_factors = []
            
            # PE估值风险
            if pe_ratio > self.risk_factors['high_pe_threshold']:
                risk_penalty = min((pe_ratio - 25) * 2, 20)
                risk_score -= risk_penalty
                risk_factors.append(f"高PE风险(-{risk_penalty:.1f})")
                
            # 市值风险（过小或过大）
            if market_cap < 50:
                risk_score -= 10
                risk_factors.append("小市值风险(-10)")
            elif market_cap > 1500:
                risk_score -= 5
                risk_factors.append("大市值风险(-5)")
                
            # 价格风险（过低可能退市）
            if current_price < 3:
                risk_score -= 15
                risk_factors.append("低价风险(-15)")
            elif current_price < 4:
                risk_score -= 8
                risk_factors.append("较低价风险(-8)")
                
            # 成长性风险
            revenue_growth = stock_info.get('revenue_growth', 0)
            profit_growth = stock_info.get('profit_growth', 0)
            
            if revenue_growth < -10 or profit_growth < -20:
                risk_score -= 10
                risk_factors.append("业绩下滑风险(-10)")
                
            # 财务健康风险
            roe = stock_info.get('roe', 10)
            if roe < 5:
                risk_score -= 8
                risk_factors.append("盈利能力弱(-8)")
                
            return {
                'risk_score': max(risk_score, -50),  # 最大风险扣分50
                'risk_factors': risk_factors
            }
            
        except Exception as e:
            print(f"评估风险因素失败: {e}")
            return {'risk_score': 0, 'risk_factors': []}
            
    def calculate_comprehensive_score(self, stock_info):
        """计算综合评分"""
        try:
            # 获取各项评分
            screening_score = stock_info.get('screening_score', 50)
            technical_score = stock_info.get('technical_score', 50)
            fundamental_score = stock_info.get('fundamental_score', 50)
            
            # 计算分红奖励
            dividend_bonus = self.calculate_dividend_bonus(stock_info)
            
            # 评估风险因素
            risk_assessment = self.assess_risk_factors(stock_info)
            risk_adjustment = risk_assessment['risk_score']
            
            # 加权综合计算
            weights = self.factor_weights
            comprehensive_score = (
                screening_score * weights['screening_score'] +
                technical_score * weights['technical_score'] +
                fundamental_score * weights['fundamental_score'] +
                dividend_bonus * weights['dividend_bonus'] +
                risk_adjustment * weights['risk_adjustment']
            )
            
            # 确保评分在合理范围内
            comprehensive_score = max(0, min(100, comprehensive_score))
            
            return {
                'comprehensive_score': round(comprehensive_score, 1),
                'dividend_bonus': dividend_bonus,
                'risk_adjustment': risk_adjustment,
                'risk_factors': risk_assessment['risk_factors']
            }
            
        except Exception as e:
            print(f"计算综合评分失败: {e}")
            return {'comprehensive_score': 50.0, 'dividend_bonus': 0, 'risk_adjustment': 0}
            
    def analyze_stock_comprehensive(self, stock_info):
        """综合分析单只股票"""
        stock_code = stock_info['code']
        stock_name = stock_info['name']
        
        print(f"\n🔍 综合评分: {stock_code} {stock_name}")
        print("-" * 60)
        
        # 显示各项评分
        print(f"   📋 筛选评分: {stock_info.get('screening_score', 0):.1f}")
        print(f"   📈 技术评分: {stock_info.get('technical_score', 0):.1f}")
        print(f"   💰 基本面评分: {stock_info.get('fundamental_score', 0):.1f}")
        
        # 计算综合评分
        comprehensive_result = self.calculate_comprehensive_score(stock_info)
        
        print(f"   💎 分红奖励: +{comprehensive_result['dividend_bonus']:.1f}")
        print(f"   ⚠️ 风险调整: {comprehensive_result['risk_adjustment']:.1f}")
        if comprehensive_result['risk_factors']:
            print(f"      风险因素: {', '.join(comprehensive_result['risk_factors'])}")
            
        print(f"   🏆 综合评分: {comprehensive_result['comprehensive_score']:.1f}/100")
        
        # 投资建议评级
        score = comprehensive_result['comprehensive_score']
        if score >= 80:
            rating = "强烈推荐"
            recommendation = "优质投资标的，建议重点关注"
        elif score >= 70:
            rating = "推荐"
            recommendation = "较好投资机会，可适量配置"
        elif score >= 60:
            rating = "中性"
            recommendation = "一般投资价值，谨慎考虑"
        elif score >= 50:
            rating = "观望"
            recommendation = "投资价值有限，建议观望"
        else:
            rating = "不推荐"
            recommendation = "投资风险较大，不建议配置"
            
        print(f"   📊 投资评级: {rating}")
        print(f"   💡 投资建议: {recommendation}")
        
        # 返回完整结果
        result = {
            **stock_info,
            **comprehensive_result,
            'investment_rating': rating,
            'investment_recommendation': recommendation
        }
        
        return result
        
    def run_comprehensive_ranking(self):
        """运行综合评分与排序系统"""
        self.print_header("第五步：综合评分与排序 - 多因子评分模型")
        
        # 加载基本面分析结果
        fundamental_results = self.load_fundamental_results()
        if not fundamental_results:
            print("❌ 无法加载基本面分析结果，请先执行第四步")
            return []
            
        print(f"📋 多因子权重配置:")
        for factor, weight in self.factor_weights.items():
            print(f"   • {factor}: {weight*100:.0f}%")
            
        print(f"\n🔍 开始对 {len(fundamental_results)} 只股票进行综合评分...")
        
        comprehensive_results = []
        
        for i, stock_info in enumerate(fundamental_results, 1):
            print(f"\n[{i:2d}/{len(fundamental_results)}] 综合评分进度")
            
            result = self.analyze_stock_comprehensive(stock_info)
            if result:
                comprehensive_results.append(result)
                
        # 按综合评分排序
        comprehensive_results.sort(key=lambda x: x['comprehensive_score'], reverse=True)
        
        # 生成最终排序报告
        self.generate_final_ranking_report(comprehensive_results)
        
        return comprehensive_results
        
    def generate_final_ranking_report(self, comprehensive_results):
        """生成最终排序报告"""
        print(f"\n📊 综合评分排序结果:")
        print(f"   • 分析股票数量: {len(comprehensive_results)}")
        
        if len(comprehensive_results) > 0:
            avg_score = sum(r['comprehensive_score'] for r in comprehensive_results) / len(comprehensive_results)
            print(f"   • 平均综合评分: {avg_score:.1f}")
            
            # 按评级统计
            ratings = {}
            for result in comprehensive_results:
                rating = result['investment_rating']
                ratings[rating] = ratings.get(rating, 0) + 1
            print(f"   • 投资评级分布: {', '.join([f'{k}({v})' for k, v in ratings.items()])}")
            
            print(f"\n🏆 综合评分排序TOP10:")
            print(f"{'排名':<4} {'代码':<8} {'名称':<10} {'综合':<6} {'技术':<6} {'基本面':<8} {'分红':<6} {'评级':<8}")
            print("-" * 75)
            
            for i, result in enumerate(comprehensive_results[:10], 1):
                dividend_bonus = result['dividend_bonus']
                rating = result['investment_rating']
                print(f"{i:<4} {result['code']:<8} {result['name']:<10} "
                      f"{result['comprehensive_score']:<6.1f} {result['technical_score']:<6.1f} "
                      f"{result['fundamental_score']:<8.1f} {dividend_bonus:<6.1f} {rating:<8}")
                      
            # 重点推荐Top 3
            print(f"\n🎯 最终推荐TOP 3潜力股票:")
            top3_stocks = comprehensive_results[:3]
            
            for i, stock in enumerate(top3_stocks, 1):
                pe = stock['pe_ratio']
                dividend_yield = stock['dividend_yield']
                market_cap = stock['market_cap']
                print(f"\n   🥇 第{i}名: {stock['code']} {stock['name']} ({stock['industry']})")
                print(f"      💯 综合评分: {stock['comprehensive_score']:.1f}/100")
                print(f"      📊 技术评分: {stock['technical_score']:.1f} | 基本面评分: {stock['fundamental_score']:.1f}")
                print(f"      💰 估值信息: PE {pe:.1f} | 市值 {market_cap:.1f}亿 | 股息率 {dividend_yield:.1f}%")
                print(f"      🎖️ 投资评级: {stock['investment_rating']}")
                print(f"      💡 投资建议: {stock['investment_recommendation']}")
                
            # 投资组合建议
            print(f"\n💼 投资组合建议:")
            if len(top3_stocks) >= 3:
                total_score = sum(s['comprehensive_score'] for s in top3_stocks)
                for i, stock in enumerate(top3_stocks, 1):
                    weight = stock['comprehensive_score'] / total_score * 100
                    print(f"   • {stock['code']} {stock['name']}: 建议权重 {weight:.1f}%")
                    
            print(f"\n⚠️ 投资风险提示:")
            print(f"   • 以上分析仅供参考，不构成投资建议")
            print(f"   • 股市有风险，投资需谨慎")
            print(f"   • 建议结合个人风险承受能力进行投资决策")
            print(f"   • 建议分散投资，控制单一股票仓位")
                
        else:
            print(f"   ⚠️ 没有完成综合评分的股票")
            
    def save_final_results(self, comprehensive_results, filename="final_investment_ranking.csv"):
        """保存最终排序结果"""
        if comprehensive_results:
            # 简化数据结构用于保存
            save_data = []
            for result in comprehensive_results:
                save_record = {
                    'rank': comprehensive_results.index(result) + 1,
                    'code': result['code'],
                    'name': result['name'],
                    'industry': result['industry'],
                    'current_price': result['current_price'],
                    'market_cap': result['market_cap'],
                    'comprehensive_score': result['comprehensive_score'],
                    'screening_score': result['screening_score'],
                    'technical_score': result['technical_score'],
                    'fundamental_score': result['fundamental_score'],
                    'dividend_bonus': result['dividend_bonus'],
                    'risk_adjustment': result['risk_adjustment'],
                    'investment_rating': result['investment_rating'],
                    'pe_ratio': result['pe_ratio'],
                    'roe': result['roe'],
                    'dividend_yield': result['dividend_yield'],
                    'dividend_quality': result['dividend_quality'],
                    'has_dividend': result['has_dividend'],
                    'dividend_count': result['dividend_count']
                }
                save_data.append(save_record)
                
            df = pd.DataFrame(save_data)
            df.to_csv(filename, index=False, encoding='utf-8-sig')
            print(f"\n💾 最终排序结果已保存到 {filename}")
            return filename
        return None

if __name__ == "__main__":
    # 创建综合评分系统实例
    ranking_system = ComprehensiveRankingSystem()
    
    # 执行综合评分与排序
    results = ranking_system.run_comprehensive_ranking()
    
    # 保存最终结果
    ranking_system.save_final_results(results)
    
    print(f"\n🎉 第五步：综合评分与排序执行完成！")
    print(f"   • 成功完成 {len(results)} 只股票的综合评分")
    print(f"   • 已选出Top 3最具潜力的投资标的")
    print(f"   • 准备进入第六步：深度分析选中股票")
